package org.simplextensions.maven.simpleextensions.plugin.jaxb;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbUtil {
	public static ExtensionsConfiguration readConfiguration(File extensionsXml) {
		try {
			Unmarshaller unmarshaller = ObjectFactory.getJaxbContext().createUnmarshaller();
			JAXBElement element = (JAXBElement) unmarshaller.unmarshal(extensionsXml);
			ExtensionsConfiguration configuration = (ExtensionsConfiguration) element.getValue();
			return configuration;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void saveConfiguration(ExtensionsConfiguration configuration, File extensionsXml) {
		try {
			JAXBElement<ExtensionsConfiguration> extensions = ObjectFactory.createExtensions(configuration);
			Marshaller marshaller = ObjectFactory.getJaxbContext().createMarshaller();
			FileOutputStream fos = new FileOutputStream(extensionsXml);
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
					"http://simplextensions.googlecode.com/svn/trunk/sx/core/src/main/resources/xsd/extensions.xsd");
			marshaller.marshal(extensions, fos);
			fos.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
